package org.hawk.gwt.ppc;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import junit.framework.TestCase;

import org.hawk.gwt.ppc.javacc.ParseException;

public class ProcessingUnitsManagerTestCase extends TestCase {
	public void testPreprocess() throws ParseException, IOException{
		String war = System.getProperty("hawk.gwt.ppc.war_dir");
		CmdArgs argsProcessor = new CmdArgs(new String[]{
			"-Preflect=org.hawk.gwt.ppc.mock.**",
			"-Pkeep-preprocessed-sources","-war", war == null ? "./bin" : war,"org.hawk.gwt.ppc.mock.mock"});
		Environment env = Environment.getInstance();
		env.configure(argsProcessor);
		try {
			ProcessingUnitsManager.getInstance().run();
			assertEquals(new File("./src/org/hawk/gwt/ppc/mock/client"),
					new File(war != null ? war : "./bin", "/gwt-ppc/org/hawk/gwt/ppc/mock/client"));
		} finally {
			ProcessingUnitsManager.getInstance().dispose();
		}
	}
	
	private void assertEquals(File expected, File actual) throws IOException{
		if(expected.isDirectory()){
			assertEquals(expected.getName(),actual.getName());
			assertTrue(actual+" is not a dir",actual.isDirectory());
			for(String sub : expected.list()){
				if(sub.equals(".svn"))continue;
				assertEquals(new File(expected,sub), 
						new File(actual,sub));
			}
			return;
		}
		assertTrue(actual+" is not exists",actual.exists());
		assertTrue(expected+" is not exists",expected.exists());
		String expectedContent = getContent(expected);
		expectedContent = expectedContent.substring(0,expectedContent.lastIndexOf('}'));
		assertTrue(actual.toString(),getContent(actual).startsWith(expectedContent));
	}

	private String getContent(File file) throws IOException {
		FileReader reader = new FileReader(file);
		StringBuilder result = new StringBuilder();
		char[] buf = new char[4096];
		int len = 0;
		while((len = reader.read(buf))>0){
			result.append(buf,0,len);
		}
		reader.close();
		if(file.getName().endsWith(".xml")){
			return result.toString()
				.replaceAll("[\n\b\t\r]", "")
				.replace('\'', '"');
		}
		return result.toString();
	}
}
